package com.qf.controller;

import com.qf.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


/**
 * projectName: wokepase1
 *
 * @author: 强力
 * time: 2021/9/7 11:23
 * description:
 */
@Controller
public class LoginController {
    /**
     * 登录方法
      * @return
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public Result login(String username, String password, boolean rememberMe) {
        //1.获取shiro中的subject对象
        Subject subject = SecurityUtils.getSubject();

        //对用户从网页输入的密码加密
        //第一个参数,明文,第二个参数,盐值,第三:hash算法执行的次数
        password = new Md5Hash(password, username, 1024).toString();
        System.out.println("-----加密---" + password);

        //2.创建shiro中的用户名和密码对象,将用户输入的用户名密码交给shiro管理
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        //3.记住关于我的设置
        System.out.println("=======记住我=======" + rememberMe);
        if (rememberMe) {
            //设置使用cookie记住用户输入的用户名密码
            token.setRememberMe(true);
        }

        //4.调用shiro的登录方法,调用后,shiro会执行Realm实现类
        try {
            subject.login(token);
            System.out.println("=====登录成功开始执行=====");
        } catch (UnknownAccountException e) {
            return  new Result(1,"账号不存在");
       } catch (IncorrectCredentialsException e) {
            return  new Result(1,"密码错误");
        } catch (AuthenticationException e) {
            return  new Result(1,"其他错误");
        }
return new Result(0,"登录成功");
    }
}
